<template>
  <!-- 搜索工具栏-->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="菜品" prop="dname">
        <el-input v-model="searchFormModel.dname" placeholder="请输入菜品" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="searchOnSubmit">查询</el-button>
        <el-button style="background-color: pink" @click="dialogAddState=true">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%">
      <el-table-column prop="dname" label="菜品" />
      <el-table-column prop="dphotourl" label="图片" width="120px">
        <template #default="{ row }">
          <el-image
              style="width: 100px; height: 100px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2)"
              :src="'http://localhost:8085' + row.dphotourl"
              :alt="'菜品图片 - '+row.dname"
              fit="cover"
              :preview-src-list="['http://localhost:8085' + row.dphotourl]"
          >
          </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="dprice" label="价格" style="text-align: center; font-weight: bold; background-color: #f8f9fa; color: #333;">
      </el-table-column>
      <el-table-column prop="dfood" label="主要食材" style="background-color: #e9ecef; font-size: 14px;">
      </el-table-column>
      <el-table-column label="操作" width="240"> <!-- 这里将宽度从 160 增加到 200 -->
        <template #default="scope">
          <div style="display: flex; justify-content: space-around;">
            <el-button
                size="small"
                :type="scope.row.status === 1?'success' : 'primary'"
                @click="toggleLockHandler(scope.row)"
                style="margin-right: 10px;">
              <template v-if="scope.row.status === 1">
                <el-icon><Lock /></el-icon>
              </template>
              <template v-else>
                <el-icon><Unlock /></el-icon>
              </template>
              {{ scope.row.status === 1? '' : '' }}
            </el-button>
            <el-button size="small" @click="tableEditHandler(scope.$index, scope.row)" style="margin-right: 10px;">
              <el-icon><Picture /></el-icon>
            </el-button>
            <el-button size="small" @click="tableEditHandler1(scope.$index, scope.row)" style="margin-right: 10px;">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="tableDeleteHandler(scope.$index, scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page" style="padding-left: 410px">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[4,5]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogAddState" title="添加菜品" width="380">
    <div>
      <el-form ref="formAddRef"  :model="formAdd" label-width="120px">
        <el-form-item prop="dname" label="菜品">
          <el-input v-model="formAdd.dname" ></el-input>
        </el-form-item>
        <el-form-item prop="dtype" label="类型">
          <el-select v-model="formAdd.dtype" placeholder="请选择类型">
            <el-option label="家常菜" value="家常菜"></el-option>
            <el-option label="面食" value="面食"></el-option>
            <el-option label="西餐" value="西餐"></el-option>
            <el-option label="饮品" value="饮品"></el-option>
            <!-- 可以继续添加更多的菜品类型 -->
          </el-select>
        </el-form-item>
        <div>
        <el-form-item prop="dphotourl" label="图片">
          <input type="file" accept="image/*" ></input>
        </el-form-item>
        </div>
        <el-form-item prop="dprice" label="价格">
          <el-input v-model="formAdd.dprice" ></el-input>
        </el-form-item>
        <el-form-item prop="dfood" label="主要食材">
          <el-input v-model="formAdd.dfood" ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary"  @click="submitRegisterForm" >确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!--   编辑照片模态框-->
  <el-dialog v-model="dialogEditState" title="修改图片" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item prop="dphotourl" label="菜品照片">
          <input type="file" @change="handleFileChange" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!--   编辑模态框-->
  <el-dialog v-model="dialogEditState1" title="修改菜品" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item prop="dname" label="菜品">
          <el-input v-model="formEdit.dname" disabled></el-input>
        </el-form-item>
        <el-form-item prop="dtype" label="菜品类型">
          <el-input v-model="formEdit.dtype" disabled></el-input>
        </el-form-item>
        <el-form-item prop="dprice" label="菜品价格">
          <el-input v-model="formEdit.dprice" ></el-input>
        </el-form-item>
        <el-form-item prop="dfood" label="主要食材" style="display: none;">
          <el-input v-model="formEdit.dfood"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit1" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {Unlock,Lock,Delete,Edit,Picture} from "@element-plus/icons";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/canteen";
import axios from 'axios';
import {ElMessage, ElMessageBox} from "element-plus";
onMounted(()=>{
  info();
  getDish();
})

//分页
const currentPage = ref(1)
const pageSize = ref(4)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const  blogInfo=ref([])

const userInfo=reactive({
  'mid':'',
})
const mallidvalue = ref([])
const info = async () => {
  // 从 sessionStorage 取出数据
  const loginUser = sessionStorage.getItem("loginUser");
  if (loginUser) {
    // 更新 userInfo.username
    const userobj = JSON.parse(loginUser)
    userInfo.mid = userobj.mid;
    console.log(userInfo.mid)
    formAdd.mallid = userInfo.mid;  // 直接在这里设置 formAdd 的 mallid 值
  }
}

// 表格显示内容
const getDish = () => {
  const params={
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  };
  // 模糊查询
  if (searchFormModel.dname && searchFormModel.dname.trim() !== '') {
    params.dname = searchFormModel.dname.trim();
  }
  if (userInfo.mid != null){
    params.mallid=userInfo.mid;
  }
  request({
    url: '/dishes/foods',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
        isLocked: item.status === 0 // 根据数据库中的status值设置isLocked
      }));
      totals.value = req.data.data.total;
    }
  })
}
//上架下架
function toggleLockHandler(row) {
  // 根据当前行的status值来决定前端发送的status值
  const newStatus = row.status === 1 ? 0 : 1; // 切换状态
  const requestData = {
    did: row.did,
    status: newStatus // 使用新的状态值
  };
  request({
    url: '/dishes/status', // 您的服务器端点
    method: 'put', // 注意这里的方法是小写的'put'
    data: requestData, // 传递JSON格式的数据
  }).then(response => {
    if (response.data.code === 1) {
      ElMessage.success(response.data.message);
      // 假设row是通过did来唯一标识的，更新状态
      row.status = newStatus;
      // 刷新页面数据
      getDish(); // 调用数据加载函数
    } else {
      console.log(response)
      getDish(); // 调用数据加载函数
    }
  }).catch(error => {
    ElMessage.error('请求失败');
  });
}

//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  dname:'',
})
const searchOnSubmit=()=>{
  getDish()
}
const searchOnReset=()=>{
  searchFormModel.dname=''
}
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getDish();
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getDish()
}
//删除一条
const tableDeleteHandler = (rowIndex , rowData) => {
  ElMessageBox.confirm(
      '确认删除 : ' +rowData.dname,
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {//点击了删除按钮
    request({
      method:'delete',
      url:'/dishes/del/'+rowData.did
    }).then(req=>{
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getDish()
      }
    })
  })
      .catch(() => {//点击了取消按钮
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

const formAddRef = ref()
// 增加
const formAddData = {
  dname: '',
  dtype: '',
  dphotourl: '',
  dprice: '',
  dfood: ''
};
const formAdd = reactive({...formAddData});
const dialogAddState = ref(false);
const submitRegisterForm = () => {
  //从sessionstorge中获取mid
  const loginUser = sessionStorage.getItem('loginUser');
  const user = JSON.parse(loginUser)
  const mallid = user.mid
  formAddRef.value.validate((valid) => {
    if (valid) {
      const formData = new FormData();
      formData.append('dname', formAdd.dname);
      formData.append('dtype', formAdd.dtype);
      formData.append('dprice', formAdd.dprice);
      formData.append('dfood', formAdd.dfood);
      formData.append('mallid',mallid)
      const file = document.querySelector('input[type="file"]').files[0];
      // 这里使用formAdd.dphotourl而不是DOM查询，因为formAdd已经是响应式对象
      if (file) {
        formData.append('userphoto', file);
      }

      axios({
        url: 'http://localhost:8085/file/dish', // 确保这个URL匹配你的后端接口
        method: 'post',
        data: formData,
        // 由于使用FormData，不需要手动设置Content-Type头部
      }).then(response => {
        if (response.data.errorCode === 200) {
          ElMessage.success("管理员正在快马加鞭的审核...");
          // 重置formAdd和对话框状态
          Object.assign(formAdd, formAddData);
          getDish(); // 刷新菜品列表
          dialogAddState.value = false; // 关闭对话框
        } else {
          ElMessage.error("菜品添加失败");
        }
      }).catch(error => {
        ElMessage.error("网络错误，请稍后重试");
      });
    } else {
      ElMessage({
        message: '表单填写有误',
        type: 'error',
      });
    }
  });
};

//编辑
const formEditData = {
  did:'',
  dname:'',
  dprice:'',
  dtype:'',
  dphotourl: '',
  dfood: ''
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData});
const tableEditHandler = (rowIndex, rowData) => {
  console.log("-------------");
  console.log(rowIndex);
  console.log(rowData);

  formEdit.did = rowData.did; // 指定要编辑的记录的 ID
  formEdit.dname = rowData.dname;
  formEdit.dtype = rowData.dtype;
  formEdit.dphotourl = rowData.dphotourl;
  formEdit.dfood = rowData.dfood;
  formEdit.dprice = rowData.dprice; // 初始化编辑框的价格为当前价格

  dialogEditState.value = true; // 打开编辑模态框
};
const tableEditHandler1 = (rowIndex, rowData) => {
  console.log("-------------");
  console.log(rowIndex);
  console.log(rowData);

  formEdit.did = rowData.did; // 指定要编辑的记录的 ID
  formEdit.dname = rowData.dname;
  formEdit.dtype = rowData.dtype;
  formEdit.dphotourl = rowData.dphotourl;
  formEdit.dfood = rowData.dfood;
  formEdit.dprice = rowData.dprice; // 初始化编辑框的价格为当前价格

  dialogEditState1.value = true; // 打开编辑模态框
};
const dialogEditState = ref(false)
const dialogEditState1 = ref(false)
// 编辑模态框的确认按钮点击事件处理函数
const dialogEditOnSubmit1 = () => {
  request({
    url: '/dishes/update',
    method: 'put',
    data: formEdit,
  }).then(req => {
    console.log(req);
    ElMessage({
      type: 'info',
      message: req.data.msg
    });
    if (200 == req.data.errorCode) {
      getDish();
    }
  });
  dialogEditState1.value = false;
};

const dialogEditOnReset = () => {
  Object.assign(formEdit, formEditData);
  dialogEditState.value = false;
};
const dialogEditOnSubmit = async () => {
  const formData = new FormData();

  if (formEdit.userphoto) {
    formData.append('userphoto', formEdit.userphoto);
  }
  // 获取 did
  const did = formEdit.did;
  try {
    const response = await axios.post(`http://localhost:8085/file/rephoto?did=${did}`, formData);
    if (response.status === 200) {
      ElMessage({
        type:'success',
        message: '修改成功'
      });
      getDish();
    } else {
      ElMessage({
        type: 'error',
        message: '修改失败'
      });
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请求失败'
    });
  }

  dialogEditState.value = false;
};
// 新增图片上传相关的处理函数
// 处理文件选择的变化
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    formEdit.userphoto = file;
  }
};


</script>

<style scoped>

</style>